package com.example.airoles.service;

import com.example.airoles.dto.ConversationSession;
import com.example.airoles.dto.ChatRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ConversationAnalyticsService {
    
    private static final Logger logger = LoggerFactory.getLogger(ConversationAnalyticsService.class);
    
    @Autowired
    private ConversationSessionService sessionService;
    
    @Autowired
    private UserProfileService userProfileService;
    
    public ConversationInsights analyzeConversation(ConversationSession session) {
        ConversationInsights insights = new ConversationInsights();
        insights.sessionId = session.sessionId;
        insights.userId = session.userId;
        insights.analysisTimestamp = LocalDateTime.now();
        
        if (session.messages == null || session.messages.isEmpty()) {
            return insights;
        }
        
        insights.messageCount = session.messages.size();
        // Removed emotion detection and progress indicators
        
        logger.debug("Analyzed conversation session: {}", session.sessionId);
        return insights;
    }
    
    public UserConversationSummary getUserConversationSummary(String userId, int days) {
        List<ConversationSession> userSessions = sessionService.getUserSessions(userId);
        LocalDateTime cutoff = LocalDateTime.now().minusDays(days);
        
        List<ConversationSession> recentSessions = userSessions.stream()
                .filter(s -> s.lastActiveAt.isAfter(cutoff))
                .collect(Collectors.toList());
        
        UserConversationSummary summary = new UserConversationSummary();
        summary.userId = userId;
        summary.periodDays = days;
        summary.totalSessions = recentSessions.size();
        summary.totalMessages = recentSessions.stream()
                .mapToInt(s -> s.messages.size())
                .sum();
        
        // Analyze role usage
        summary.roleUsage = recentSessions.stream()
                .collect(Collectors.groupingBy(
                    s -> s.roleId,
                    Collectors.counting()
                ));
        
        return summary;
    }
    
    public SystemAnalytics getSystemAnalytics() {
        SystemAnalytics analytics = new SystemAnalytics();
        analytics.timestamp = LocalDateTime.now();
        
        Map<String, Object> userStats = userProfileService.getSystemStats();
        analytics.totalUsers = ((Number) userStats.get("totalUsers")).longValue();
        analytics.activeUsersToday = ((Number) userStats.get("activeToday")).longValue();
        analytics.totalConversations = ((Number) userStats.get("totalConversations")).intValue();
        
        analytics.popularRoles = getPopularRoles();
        analytics.popularSkills = getPopularSkills();
        
        return analytics;
    }
    
    private Map<String, Integer> getPopularRoles() {
        return Map.of(
            "life_coach", 45,
            "therapist", 32,
            "wise_mentor", 28,
            "philosopher", 21
        );
    }
    
    private Map<String, Integer> getPopularSkills() {
        return Map.of(
            "active_listening", 38,
            "perspective_shift", 31,
            "emotion_processing", 29,
            "value_clarification", 24
        );
    }
    
    // Data classes for analytics results
    public static class ConversationInsights {
        public String sessionId;
        public String userId;
        public LocalDateTime analysisTimestamp;
        public int messageCount;
    }
    
    public static class UserConversationSummary {
        public String userId;
        public int periodDays;
        public int totalSessions;
        public int totalMessages;
        public Map<String, Long> roleUsage;
    }
    
    public static class SystemAnalytics {
        public LocalDateTime timestamp;
        public long totalUsers;
        public long activeUsersToday;
        public int totalConversations;
        public Map<String, Integer> popularRoles;
        public Map<String, Integer> popularSkills;
    }
}